package utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;

public class Utils {

	public static String deserializeString(File file) {
		int len;
		char[] chr = new char[4096];
		final StringBuffer buffer = new StringBuffer();
		FileReader reader = null;
		try {
			reader = new FileReader(file);
			while ((len = reader.read(chr)) > 0) {
				buffer.append(chr, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				reader.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return buffer.toString();
	}

	public byte[] getBytesFromFile(File file) throws IOException {
		if (!file.exists()) {
			return null;
		}

		// get the size of the file
		long length = file.length();
		if (length > Integer.MAX_VALUE) {
			throw new IOException(String.format(
					"The file %s is too large to be hold in a byte array",
					file.getName()));
		}

		int len = (int) length;
		byte[] bytes = new byte[len];

		InputStream in = new FileInputStream(file);

		// read in the bytes
		int offset = 0, n = 0;
		while (offset < len && n >= 0) {
			n = in.read(bytes, offset, len - offset);
			offset += n;
		}

		if (offset < len) {
			throw new IOException("Faile to read all contents of file: "
					+ file.getName());
		}

		in.close();
		return bytes;
	}
}
